class Solution
{
public:
    int countMatchingSubarrays(vector<int> &nums, vector<int> &pattern)
    {
        vector<int> numPattern;
        int n = nums.size() - 1;
        for (int i = 0; i < n; i++)
        {
            int diff = nums[i + 1] - nums[i];
            if (diff > 0)
            {
                numPattern.push_back(1);
            }
            else if (diff < 0)
            {
                numPattern.push_back(-1);
            }
            else
            {
                numPattern.push_back(0);
            }
        }

        vector<int> next(pattern.size(), -1);
        for (int i = 1, j = -1; i < pattern.size(); i++)
        {
            while (j != -1 && pattern[i] != pattern[j + 1])
            {
                j = next[j];
            }
            if (pattern[i] == pattern[j + 1])
            {
                j++;
            }
            next[i] = j;
        }

        int result = 0;
        for (int i = 0, j = -1; i < numPattern.size(); i++)
        {
            while (j != -1 && numPattern[i] != pattern[j + 1])
            {
                j = next[j];
            }
            if (numPattern[i] == pattern[j + 1])
            {
                j++;
            }
            if (j == pattern.size() - 1)
            {
                result++;
                j = next[j];
            }
        }
        return result;
    }
};